<template>
  <div v-loading="loading">
    <el-table :data="tableData" :border="true" class="weekly-table" :highlight-current-row="false">
      <el-table-column prop="mealTypeName" label="餐别" :width="getViewportPx(120)" fixed />
      <el-table-column
        v-for="(day, index) in displayedWeekDays"
        :key="index"
        :prop="'day' + day.value"
        :label="day.date ? `${day.label}(${day.date})` : day.label"
        :min-width="250"
        :width="getViewportPx(308)"
        class-name="!vertical-top"
      >
        <template #header>
          <div class="header-cell">
            <div class="day-label">{{ day.date ? `${day.label}(${day.date})` : day.label }}</div>
            <div class="sub-table-header">
              <span class="sub-header-item" style="width: 50%">食谱</span>
              <span class="sub-header-item" style="width: 50%">带量/人（克）</span>
            </div>
          </div>
        </template>
        <template #default="scope">
          <div class="recipe-cell rounded h-full -mx-12px">
            <el-table :data="scope.row[`day${day.value}`]" class="inner-table" :show-header="false" empty-text="无">
              <el-table-column prop="recipeName" label="食谱" :width="getViewportPx(130)" class-name="!vertical-top"/>
              <el-table-column label="带量/人（克）">
                <template #default="innerScope">
                  <div
                    v-for="(usage, usageIndex) in innerScope.row.usagesList"
                    :key="usageIndex"
                    class="usage-item flex justify-between items-center mb-2px"
                  >
                    <span class="food-name text-14px">{{ usage.foodName }}</span>
                    <span class="food-usage text-12px text-gray-500 flex-shrink-0"
                      >{{ usage.usage }}克</span
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { formatDate } from '@/utils/formatTime'
import { getWeekStartDate, formatMonthDay } from '../utils/dateUtils'
import { RecipeMenusDailyApi } from '@/api/school/recipe/menusDaily'
import { getViewportPx } from '@/utils/formatter'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

// 定义组件属性
const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  currentWeeklyMenu: {
    type: Object,
    default: () => ({})
  }
})

// 定义事件
const emit = defineEmits(['update:loading'])

const message = useMessage()

// 带量统计数据
const quantityData = ref<any[]>([])

// 所有星期选项
const allWeekDays = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 }
]

// 实际需要展示的星期选项（根据 quantityData 中的数据）
const displayedWeekDays = computed(() => {
  // 创建一个映射，将weekDay值映射到日期
  const dateMap: Record<string, string> = {}

  // 从quantityData中获取日期信息
  if (quantityData.value && quantityData.value.length > 0) {
    quantityData.value.forEach((item: any) => {
      if (item.weekDay) {
        const dayIndex = parseInt(item.weekDay)
        if (item.menuDate) {
          dateMap[dayIndex] = formatDate(new Date(item.menuDate), 'MM.DD')
        }
      }
    })
  }

  // 如果quantityData中没有足够的数据，从currentWeeklyMenu中计算日期
  if (
    props.currentWeeklyMenu &&
    props.currentWeeklyMenu.weekYear &&
    props.currentWeeklyMenu.weekNumber
  ) {
    // 计算这一周的每一天日期
    const startDate = getWeekStartDate(
      props.currentWeeklyMenu.weekYear,
      props.currentWeeklyMenu.weekNumber
    )

    allWeekDays.forEach((day) => {
      // 如果dateMap中还没有这个日期，则计算并添加
      if (!dateMap[day.value]) {
        const currentDate = new Date(startDate)
        currentDate.setDate(startDate.getDate() + day.value - 1) // 周一为第一天
        dateMap[day.value] = formatMonthDay(currentDate)
      }
    })
  }

  // 只返回 quantityData 中实际存在的日期
  const result: { label: string; value: number; date: string }[] = quantityData.value
    .map((item: any) => {
      const dayIndex = parseInt(item.weekDay)
      const day = allWeekDays.find((d) => d.value === dayIndex)
      return day
        ? {
            ...day,
            date: dateMap[day.value] || ''
          }
        : null
    })
    .filter((item): item is { label: string; value: number; date: string } => item !== null) // 过滤掉 null 值并确保类型安全

  // 按照星期顺序排序
  return result.sort((a, b) => a.value - b.value)
})

// 表格数据
const tableData = computed(() => {
  // 获取餐别字典
  const mealTypeDict = getStrDictOptions(DICT_TYPE.SCHOOL_MEAL_TYPE)

  // 获取所有唯一的餐别
  const mealTypes: string[] = []
  quantityData.value.forEach((dayData) => {
    if (dayData.mealList) {
      dayData.mealList.forEach((meal: any) => {
        if (!mealTypes.includes(meal.mealType)) {
          mealTypes.push(meal.mealType)
        }
      })
    }
  })

  // 为每一餐别填充每天的数据
  const rows: any[] = []
  mealTypes.forEach((mealType) => {
    const mealTypeDictItem = mealTypeDict.find((dict) => dict.value === mealType)
    const row: any = {
      mealType: mealType,
      mealTypeName: mealTypeDictItem ? mealTypeDictItem.label : mealType
    }

    displayedWeekDays.value.forEach((day) => {
      // 查找当天该餐别的数据
      const dayData = quantityData.value.find((item) => parseInt(item.weekDay) === day.value)
      if (dayData && dayData.mealList) {
        const mealData = dayData.mealList.find((meal: any) => meal.mealType === mealType)
        row[`day${day.value}`] = mealData ? mealData.recipeList : []
      } else {
        row[`day${day.value}`] = []
      }
    })

    rows.push(row)
  })

  return rows
})

// 加载带量统计数据
const loadQuantityData = async (menuId: number) => {
  emit('update:loading', true)
  try {
    const res = await RecipeMenusDailyApi.getRecipeMenusDailyUsage(menuId)
    quantityData.value = res || []
  } catch (err) {
    message.error('加载带量统计数据失败')
  } finally {
    emit('update:loading', false)
  }
}

// 监听currentWeeklyMenu变化，当menuId改变时重新加载数据
watch(
  () => props.currentWeeklyMenu?.menuId,
  async (newMenuId, oldMenuId) => {
    if (newMenuId && newMenuId !== oldMenuId) {
      await loadQuantityData(newMenuId)
    }
  },
  { immediate: true }
)

// 暴露方法给父组件
defineExpose({
  loadQuantityData
})
</script>

<style lang="scss" scoped>
.weekly-table {
  width: fit-content;

  :deep(.el-table__cell) {
    padding: 8px 0;
  }

  :deep(.el-table__body tr:hover > td) {
    background-color: inherit !important;
  }

  :deep(.inner-table .el-table__cell) {
    padding: 4px 0;
  }

  :deep(.inner-table) {
    .el-table__cell {
      border: none !important;
    }
  }

  .recipe-cell {
    height: 100%;

    :deep() {
      .el-table__inner-wrapper {
        &::before {
          display: none;
        }
      }
    }
  }

  .usage-item {
    display: flex;
    justify-content: space-between;
  }

  .header-cell {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .day-label {
    margin-bottom: 8px;
  }

  .sub-table-header {
    display: flex;
    width: 100%;
    padding-top: 8px;
    border-top: 1px solid #ebeef5;
  }

  .sub-header-item {
    font-size: 12px;
    font-weight: normal;
    color: #909399;
    text-align: left;
  }
}
</style>
